package com.yyfax.ph.home.recommendloan.creditinfo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.ph.R;
import com.yyfax.ph.base.BaseFragment;
import com.yyfax.ph.base.dialog.DialogBase;
import com.yyfax.ph.home.recommendloan.PageDownEvent;
import com.yyfax.ph.home.recommendloan.RecommendLoanActivity;
import com.yyfax.ph.main.MainActivity;
import com.yyfax.ph.progress.supplement.SupplementPresenter;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 有无征信报告Fragment
 * Created by ying_he on 2017/11/3.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */

public class UploadCreditPaperFragment extends BaseFragment implements UploadCreditPaperPresenter.View, SupplementPresenter.View {
	private static final String TAG = UploadCreditPaperFragment.class.getSimpleName();
	public static final int BIZ_TYPE_HAS_CREDIT_RECOMMEND_UPLOAD = 0; // 有征信推荐上传
	public static final int BIZ_TYPE_NO_CREDIT_RECOMMEND_UPLOAD = 1; // 无征信推荐上传
	public static final int BIZ_TYPE_HAS_CREDIT_SUPPLEMENT_UPLOAD = 2; // 有征信补件上传
	public static final int BIZ_TYPE_NO_CREDIT_SUPPLEMENT_UPLOAD = 3; // 无征信补件上传
	public static final String BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT = "extra_params_to_upload_credit";

	private static final int LOADER_ID_UPLOAD_CREDIT = 10015;
	private static final int LOADER_ID_UPLOAD_SUPPLEMENT = 10016;
	private static final String FRAGMENT_TAG_HAS_CREDIT_PAPER = "tag_has_credit_paper";
	private static final String FRAGMENT_TAG_NO_CREDIT_PAPER = "tag_no_credit_paper";
	Unbinder mUnBinder;
	@BindView(R.id.submit_tv)
	TextView mSubmitTv;
	ExtraParamsToUploadCredit mExtraParamsToUploadCredit;
	private Fragment mHasCreditPaperFragment;
	private Fragment mNoCreditPaperFragment;
	private UploadCreditPaperPresenter mUploadCreditPaperPresenter;
	private SupplementPresenter mSupplementPresenter;

	/**
	 * @param extraParamsToUploadCredit 无征信推荐时,基本资料页传递到本页面的身份证正反面照片资料, 从补件或有征信可不传
	 * @return
	 */
	public static Fragment newInstance(UploadCreditPaperFragment.ExtraParamsToUploadCredit extraParamsToUploadCredit) {
		Fragment fragment = new UploadCreditPaperFragment();
		Bundle bundle = new Bundle();
		bundle.putParcelable(BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT, extraParamsToUploadCredit);
		fragment.setArguments(bundle);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		getLoaderManager().initLoader(LOADER_ID_UPLOAD_CREDIT, null, this);
		getLoaderManager().initLoader(LOADER_ID_UPLOAD_SUPPLEMENT, null, this);
	}

	@Override
	public void onDetach() {
		super.onDetach();
		getLoaderManager().destroyLoader(LOADER_ID_UPLOAD_CREDIT);
		getLoaderManager().destroyLoader(LOADER_ID_UPLOAD_SUPPLEMENT);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_UPLOAD_CREDIT:
				return new PresenterLoader<>(getActivity(), new UploadCreditPaperPresenter.Generator());
			case LOADER_ID_UPLOAD_SUPPLEMENT:
				return new PresenterLoader<>(getActivity(), new SupplementPresenter.Generator());
			default:
				return null;
		}
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_UPLOAD_CREDIT:
				mUploadCreditPaperPresenter = (UploadCreditPaperPresenter) data;
				mUploadCreditPaperPresenter.attach(this);
				break;
			case LOADER_ID_UPLOAD_SUPPLEMENT:
				mSupplementPresenter = (SupplementPresenter) data;
				mSupplementPresenter.attach(this);
				break;
			default:
				break;
		}
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_upload_credit_paper, null);
		mUnBinder = ButterKnife.bind(this, view);
		return view;
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		EventAgent.register(this);
		if (savedInstanceState != null) {
			mExtraParamsToUploadCredit = savedInstanceState.getParcelable(BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT);
		} else {
			mExtraParamsToUploadCredit = getArguments().getParcelable(BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT);
		}
		initView();
	}

	private void initView() {
		if (mExtraParamsToUploadCredit == null) {
			return;
		}
		if (mSubmitTv != null) {
			if (mExtraParamsToUploadCredit.bizType == BIZ_TYPE_NO_CREDIT_SUPPLEMENT_UPLOAD || mExtraParamsToUploadCredit.bizType == BIZ_TYPE_HAS_CREDIT_SUPPLEMENT_UPLOAD) {
				mSubmitTv.setVisibility(View.VISIBLE);
			} else {
				mSubmitTv.setVisibility(View.GONE);
			}
		}

		FragmentManager fm = getActivity().getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		mHasCreditPaperFragment = fm.findFragmentByTag(FRAGMENT_TAG_HAS_CREDIT_PAPER);
		mNoCreditPaperFragment = fm.findFragmentByTag(FRAGMENT_TAG_NO_CREDIT_PAPER);
		if (mHasCreditPaperFragment != null) {
			ft.hide(mHasCreditPaperFragment);
		}
		if (mNoCreditPaperFragment != null) {
			ft.hide(mNoCreditPaperFragment);
		}

		switch (mExtraParamsToUploadCredit.bizType) {
			case BIZ_TYPE_HAS_CREDIT_RECOMMEND_UPLOAD: // 有征信推荐上传
			case BIZ_TYPE_HAS_CREDIT_SUPPLEMENT_UPLOAD: // 有征信补件上传
				if (mHasCreditPaperFragment == null) {
					mHasCreditPaperFragment = HasCreditPaperFragment.newInstance(mExtraParamsToUploadCredit);
					ft.add(R.id.fragment_container_fl, mHasCreditPaperFragment, FRAGMENT_TAG_HAS_CREDIT_PAPER);
				} else {
					ft.show(mHasCreditPaperFragment);
				}
				break;
			case BIZ_TYPE_NO_CREDIT_RECOMMEND_UPLOAD: // 无征信推荐上传
			case BIZ_TYPE_NO_CREDIT_SUPPLEMENT_UPLOAD: // 无征信补件上传
				if (mNoCreditPaperFragment == null) {
					mNoCreditPaperFragment = NoCreditPaperFragment.newInstance(mExtraParamsToUploadCredit);
					ft.add(R.id.fragment_container_fl, mNoCreditPaperFragment, FRAGMENT_TAG_NO_CREDIT_PAPER);
				} else {
					((NoCreditPaperFragment)mNoCreditPaperFragment).refreshIdCard(mExtraParamsToUploadCredit);
					ft.show(mNoCreditPaperFragment);
				}
				break;
			default:
				break;
		}
		ft.commitAllowingStateLoss();
	}

	public void changeFragment(UploadCreditPaperFragment.ExtraParamsToUploadCredit extraParamsToUploadCredit) {
		if (extraParamsToUploadCredit != null) {
			mExtraParamsToUploadCredit = extraParamsToUploadCredit;
			initView();
		}
	}

	/**
	 * 提交推荐征信报告
	 *
	 * @param rcmId
	 * @param imageIds
	 */
	public void uploadRecommendCredit(String rcmId, List<String> imageIds) {
		mUploadCreditPaperPresenter.uploadCreditPaper(rcmId, imageIds, mExtraParamsToUploadCredit.bizType);
	}

	/**
	 * 提交补件征信报告
	 *
	 * @param rcmId    推荐编号
	 * @param imageIds 图片id
	 */
	public void uploadSupplementCredit(String rcmId, List<String> imageIds) {
		mSupplementPresenter.uploadCredit(rcmId, imageIds);
	}

	@OnClick({R.id.submit_tv})
	public void onClicked(View view) {
		// 补件上传需使用这个按钮.
		// 推荐上传则使用里面的按钮.
		switch (mExtraParamsToUploadCredit.bizType){
			case BIZ_TYPE_HAS_CREDIT_RECOMMEND_UPLOAD: // 有征信推荐上传
			case BIZ_TYPE_HAS_CREDIT_SUPPLEMENT_UPLOAD: // 有征信补件上传
				((HasCreditPaperFragment) mHasCreditPaperFragment).confirm();
				break;
			case BIZ_TYPE_NO_CREDIT_RECOMMEND_UPLOAD: // 无征信推荐上传
			case BIZ_TYPE_NO_CREDIT_SUPPLEMENT_UPLOAD: // 无征信补件上传
				((NoCreditPaperFragment) mNoCreditPaperFragment).submitCredit();
				break;
			default:
				break;
		}

	}

	/**
	 * 跳转其他资料页面
	 */
	private void switchToUploadOtherInfoFragment() {
		ExtraParamsToUploadCredit extraParamsToUploadCredit = getArguments().getParcelable(BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT);
		if (extraParamsToUploadCredit != null) {
			EventAgent.post(new PageDownEvent(RecommendLoanActivity.PAGE_OTHER_INFO, extraParamsToUploadCredit.rcmId));
		}
	}

	@Override
	public void onCancelSuccess(String tips) {

	}

	@Override
	public void onCancelFailure(String tips) {

	}

	@Override
	public void onCancelFailureExit(String tips) {

	}

	@Override
	public void uploadCreditSuccess(String msg) {
		switchToUploadOtherInfoFragment();
	}

	@Override
	public void onUploadSuccess(String tips) {
		showToast(tips);
		MainActivity.startToProgressSearch(getActivity());
	}

	@Override
	public void uploadCreditFailed(String tips) {
		showToast(tips);
	}

	@Override
	public void onUploadFailure(String tips) {
		showToast(tips);
	}

	@Override
	public void onUploadFailureExit(String tips) {
		new DialogBase(getActivity(), tips, null, getResources().getString(
				R.string.confirm), new DialogBase.BottomOneClickListener() {
			@Override
			public void bottomOneClick(DialogBase dialog) {
				dialog.dismiss();
				MainActivity.startToProgressSearch(getActivity());//补件失败表示推荐状态有更新，退回到进度查询界面需要刷新
			}
		}, false).show();

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (mExtraParamsToUploadCredit.bizType){
			case BIZ_TYPE_HAS_CREDIT_RECOMMEND_UPLOAD: // 有征信推荐上传
			case BIZ_TYPE_HAS_CREDIT_SUPPLEMENT_UPLOAD: // 有征信补件上传
				mHasCreditPaperFragment.onActivityResult(requestCode, resultCode, data);
				break;
			case BIZ_TYPE_NO_CREDIT_RECOMMEND_UPLOAD: // 无征信推荐上传
			case BIZ_TYPE_NO_CREDIT_SUPPLEMENT_UPLOAD: // 无征信补件上传
				mNoCreditPaperFragment.onActivityResult(requestCode, resultCode, data);
				break;
			default:
				break;
		}
	}


	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onMessageEvent(UploadCreditPaperEvent uploadCreditPaperEvent) {
		switch (uploadCreditPaperEvent.bizType) {
			case BIZ_TYPE_NO_CREDIT_RECOMMEND_UPLOAD:
			case BIZ_TYPE_HAS_CREDIT_RECOMMEND_UPLOAD:
				uploadRecommendCredit(uploadCreditPaperEvent.rcmId, uploadCreditPaperEvent.imageIds);
				break;
			case BIZ_TYPE_HAS_CREDIT_SUPPLEMENT_UPLOAD:
			case BIZ_TYPE_NO_CREDIT_SUPPLEMENT_UPLOAD:
				uploadSupplementCredit(uploadCreditPaperEvent.rcmId, uploadCreditPaperEvent.imageIds);
				break;
			default:
				break;
		}
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		EventAgent.unregister(this);
		mUnBinder.unbind();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putParcelable(BUNDLE_KEY_EXTRA_PARAMS_TO_UPLOAD_CREDIT, mExtraParamsToUploadCredit);
	}

	public static class UploadCreditPaperEvent {
		/**
		 * 业务类型:有无征信上传, 有无征信补件上传.
		 * 取值请跳转查看:{@link this.BIZ_TYPE_HAS_CREDIT_RECOMMEND_UPLOAD}
		 */
		public int bizType = -1;
		public String flag = "";
		public List<String> imageIds = new ArrayList<>();
		public String rcmId = "";
		public String remark = "";
	}

	/**
	 * 从基本信息页面跳转到征信页面传递的额外信息
	 */
	public static class ExtraParamsToUploadCredit implements Parcelable {
		public static final Creator<ExtraParamsToUploadCredit> CREATOR = new Creator<ExtraParamsToUploadCredit>() {
			@Override
			public ExtraParamsToUploadCredit createFromParcel(Parcel in) {
				return new ExtraParamsToUploadCredit(in);
			}

			@Override
			public ExtraParamsToUploadCredit[] newArray(int size) {
				return new ExtraParamsToUploadCredit[size];
			}
		};
		public String idFrontImgPath = ""; // 身份证扫描正面图片保存地址
		public String idBackImgPath = ""; // 身份证扫描反面图片保存地址
		public String rcmId = ""; // 推荐码
		/**
		 * // 表征是有征信推荐还是无征信推荐跳转.
		 * {@link this.BIZ_TYPE_HAS_CREDIT_RECOMMEND_UPLOAD}
		 * {@link this.BIZ_TYPE_NO_CREDIT_RECOMMEND_UPLOAD}
		 */
		public int bizType = -1;

		public ExtraParamsToUploadCredit() {

		}

		protected ExtraParamsToUploadCredit(Parcel in) {
			idFrontImgPath = in.readString();
			idBackImgPath = in.readString();
			rcmId = in.readString();
			bizType = in.readInt();
		}

		@Override
		public void writeToParcel(Parcel parcel, int i) {
			parcel.writeString(idFrontImgPath);
			parcel.writeString(idBackImgPath);
			parcel.writeString(rcmId);
			parcel.writeInt(bizType);
		}

		@Override
		public int describeContents() {
			return 0;
		}
	}
}
